package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        //1.接收参数
        log.info(dishDto.toString());
        //2.保存数据
        dishService.saveWithFlavor(dishDto);
        //清理缓存（全清理）（清理指定的缓存）
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     * @param page  基本的菜品分页
     * @param pageSize  每页大小
     * @param name  基本的菜品分页 - 分类的name
     * @return  /dish/page?page=1&pageSize=10&name=%E5%A4%A7
     */
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        log.info("page:{},pageSize:{},name:{}",page,pageSize,name);

        //1构建分页
        IPage<Dish> dishPage = new Page<>(page, pageSize);
        //2构建条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Dish::getName,name);
        wrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getUpdateTime);
        //3分页查询
        dishService.page(dishPage,wrapper);
        //4. IPage<DishDto>
        IPage<DishDto> dishDtoPage = new Page<>(page, pageSize);
        //5. 分页基本数据：当前页、总条数...
        //对象copy（本质getter/setter）  参数：源对象、目标对象、忽略的属性
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //6. records中的数据:
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtoList = records.stream().map(item -> {//item=dish
            DishDto dishDto = new DishDto();
        //dish基本数据：name id image...
            BeanUtils.copyProperties(item,dishDto);
        //categoryName? 通过cid 去查询name
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();

            dishDto.setCategoryName(categoryName);
        //收集成新的集合
            return dishDto;
        }).collect(Collectors.toList());

        //7. 封装好的这个数据集合要放到IPage<DishDto>  records上
        dishDtoPage.setRecords(dishDtoList);
        //8.返回数据
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        //1.获取信息
        log.info(dishDto.toString());
        //2.修改
        dishService.updateWithFlavor(dishDto);
        //清理缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        //3.返回结果
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> delete(Long[] ids){
        //1.接收信息
        log.info("删除id为:{}",ids);
        //2.删除
        dishService.removeByIds(Arrays.asList(ids));

        return R.success("删除成功");
    }

    /**
     * 批量停售/起售
     * @param status    修改状态
     * @param ids       根据id修改
     * @return          返回结果
     */
    @PostMapping("/status/{status}")
    public R<String> upstatus(@PathVariable ("status") Integer status,@RequestParam List<Long> ids){
        //1.接收信息
        log.info("修改的status，ids为:{}",status,ids);
        //2.修改状态
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ids !=null,Dish::getId,ids);
        //根据数据进行批量查询
        List<Dish> list = dishService.list(wrapper);
        for (Dish dish : list){
            if (dish != null){
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        //返回结果
        return R.success("售卖状态修改成功");
    }

    @GetMapping("/list")
    public R list(Dish dish){
        //1.接收信息
        log.info("菜品分类为:{}",dish);
        //2.构建查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(wrapper);
        //3.解决口味问题
        //定义一个集合
        List<DishDto> dishDtos = new ArrayList<>();
        //定义一个key
        String key = "dish_"+dish.getCategoryId()+"_1";
        //从缓存中获取数据
        Object o = redisTemplate.opsForValue().get(key);
        if (o!=null){
            //数据赋值并返回
            dishDtos = (List<DishDto>)o;
            return R.success(dishDtos);
        }

        for (Dish dto : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dto,dishDto);
            //sql: select * from dish_flavor where dish_id = ?
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(dto.getId()!=null,DishFlavor::getDishId,dto.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(flavorList);
            //把dto放入到list（dishDtos）集合中
            dishDtos.add(dishDto);
        }
        //存入redis缓存（对象--->json）(jdk序列化器)
        redisTemplate.opsForValue().set(key,dishDtos,10, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }
}
